package cn.sangedon.review.data.spider.impl;

import cn.hutool.http.HttpRequest;
import cn.sangedon.review.common.domain.data.SpiderMateData;
import cn.sangedon.review.common.domain.data.StockDayInfo;
import cn.sangedon.review.common.service.data.StockDayInfoService;
import cn.sangedon.review.data.constant.SpiderEnum;
import cn.sangedon.review.data.spider.AbstractStockInfoSpider;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 深圳日交易数据爬虫
 * 仅支持每次获取十条交易数据，需要分页获取全部数据
 *
 * @author dongliangqiong
 */
@Slf4j
@Component
public class StockOfDaySzSpider extends AbstractStockInfoSpider {
    @Autowired
    private StockDayInfoService stockDayInfoService;

    @Override
    public void runJob(List<SpiderMateData> spiderMateDataList) {
        spiderMateDataList.stream().filter(e -> e.getSpiderName().equals(SpiderEnum.SZ_DAILY_HTTP.getName())).findFirst().ifPresent(e -> {
            addSchedule(e);
        });
    }

    @Override
    public void crawlData() {
        AtomicInteger index = new AtomicInteger(0);
        while (!processData() && index.getAndIncrement() < 3) {
            log.info("重试获取上证日交易数据{}次", index.intValue());
        }
    }

    private boolean processData() {
        try {
            log.info("开始获取深圳交易所日交易数据");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String spiderUrl = String.format(getSpiderMateData().getSpiderUrl(), df.format(new Date()), df.format(new Date()));
            String body = HttpRequest.get(spiderUrl).execute().body();
            JSONObject result = JSONObject.parseObject(body.substring(1, body.length() - 1));
            JSONArray data = result.getJSONArray("data");

            List<StockDayInfo> list = new ArrayList<>();
            for (Object datum : data) {
                JSONObject object = (JSONObject) datum;
                StockDayInfo stockDayInfo = new StockDayInfo();
                stockDayInfo.setName(object.getString("zqjc"));
                stockDayInfo.setCode(object.getString("zqdm"));
                stockDayInfo.setLastClosePrice(new BigDecimal(object.getString("qss").replace(",", "")));
                stockDayInfo.setClosingPrice(new BigDecimal(object.getString("ss").replace(",", "")));
                stockDayInfo.setOpeningPrice(new BigDecimal(object.getString("ks").replace(",", "")));
                stockDayInfo.setBottomPrice(new BigDecimal(object.getString("zd").replace(",", "")));
                stockDayInfo.setPeakPrice(new BigDecimal(object.getString("zg").replace(",", "")));
                stockDayInfo.setChangeRate(object.getBigDecimal("sdf"));
                stockDayInfo.setTradingDate(object.getString("jyrq"));
                stockDayInfo.setTradingAmount(new BigDecimal(object.getString("cjje").replace(",", "")));
                stockDayInfo.setTradingVolume(new BigDecimal(object.getString("cjgs").replace(",", "")));
                list.add(stockDayInfo);
            }
            stockDayInfoService.saveOrUpdateBatch(list);
            log.info("深交所日交易数据保存成功:{}", list.size());
            return true;
        } catch (Exception e) {
            log.error("获取深交所日交易数据失败:{}", e);
            return false;
        }
    }
}
